package com.myjar.excel.v2;

import com.myjar.excel.serializer.ObjectSerializer;
import com.myjar.excel.serializer.SerializerConfig;
import com.myjar.excel.util.TypeUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

// 书写标题序列化器
public class SkipSerializer implements _Serializer {

    private BeanInfo beanInfo;
    private int len;

    public SkipSerializer(BeanInfo beanInfo) {
        this.beanInfo = beanInfo;
        len = beanInfo.getFields().length;
    }

    @Override
    public <T> void write(_Context<T> context, List<T> ts) {
        try {
            writeTitle(context);
        } catch (Exception e) {
            e.printStackTrace();
            context.log(e);
        }
        for (T t : ts) {
            try {
                writeLine(context, t);
            } catch (Exception e) {
                context.log(e);
                e.printStackTrace();
                break;
            }
        }

    }

    protected <T> void writeTitle(_Context<T> context) throws Exception {
        ObjectSerializer stringCodec = SerializerConfig.get(String.class);
        for (int i = 0; i < len; i++) {
            context.setValAndToNextCell(beanInfo.getNames()[i], stringCodec);
        }
        context.toNextLineBegin();
    }

    @Override
    public <T> void read(_Context<T> context, Class<T> tClass) {
        context.toNextLineBegin();
        while (context.hasMoreRow()) {
            try {
                T t = tClass.newInstance();
                readLine(context, t);
                context.add(t);
            } catch (Exception e) {
                context.log(e);
                return;
            }
        }
    }

    @Override
    public <T> void writeLine(_Context<T> context, T t) throws Exception {

        for (int i = 0; i < len; i++) {
            ObjectSerializer objectSerializer = beanInfo.getObjectSerializers()[i];
            Object o = TypeUtils.getFieldVal(t, beanInfo.getFields()[i]);
            context.setValAndToNextCell(o, objectSerializer);
        }
        context.toNextLineBegin();
    }

    @Override
    public <T> void readLine(_Context<T> context, T t) throws Exception {
        for (int i = 0; i < len; i++) {
            ObjectSerializer objectSerializer = beanInfo.getObjectSerializers()[i];
            Object o = context.getValAndToNextCell(objectSerializer);
            TypeUtils.setFieldVal(t, beanInfo.getFields()[i], o);
        }
        context.toNextLineBegin();
    }


}
